package com.jeasonzhao.report.engine.servlet;

import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jeasonzhao.report.engine.Configuration;
import com.jeasonzhao.web.AbstractServlet;
import com.jeasonzhao.commons.utils.Algorithms;
import com.jeasonzhao.web.ServletHelper;

public class ReportServlet extends AbstractServlet
{
    private static final long serialVersionUID = 1L;
    public ReportServlet()
    {
        Configuration.getInstance();
    }

    private String getReportId(HttpServletRequest request)
    {
        if(null == request)
        {
            return null;
        }
        String reportid = null;
        String strUrl = request.getRequestURI();
        if(null != strUrl)
        {
            int n = strUrl.lastIndexOf('/');
            if(n >= 0)
            {
                strUrl = strUrl.substring(n + 1);
            }
            n = strUrl.lastIndexOf('\\');
            if(n >= 0)
            {
                strUrl = strUrl.substring(n + 1);
            }
            strUrl = strUrl.toLowerCase();
            n = strUrl.indexOf(".rpt");
            if(n > 0)
            {
                reportid = strUrl.substring(0,n);
            }
        }
        if(Algorithms.isEmpty(reportid))
        {
            reportid = ServletHelper.getParameter(request,Constants.REPORTID
                                                  ,"rptid","rpt","report");
        }
        return reportid;
    }

    public void execute(HttpServletRequest request,HttpServletResponse response)
        throws IOException
    {
        ReportServletAgent agent = new ReportServletAgent(request,response,getReportId(request));
        String strHtml = agent.execute();
        response.getWriter().write("<html>");
        response.getWriter().write("\r\n"+"<head>");
        response.getWriter().write("\r\n"+"<title>" + (null == agent.getReport() ? "No report found" : agent.getReport().getTitle()) + "</title>");
//        try
//        {
//            TagInclude a = new TagInclude();
////            response.getWriter().write("\r\n" + a.simulate());
//        }
//        catch(Exception ex)
//        {
//        }
        response.getWriter().write("\r\n"+"</head>");
        response.getWriter().write("\r\n"+"<body>");
        response.getWriter().write("\r\n"+strHtml);
        response.getWriter().write("\r\n"+"</body>");
        response.getWriter().write("\r\n"+"</html>");
    }
}
